// ==UserScript==
// @name        Tumblr Notifier
// @namespace   https://www.tumblr.com/
// @description Notifier for Tumblr - released under Apache 2.0 Licence by LazyScripter
// @downloadURL http://lazyscripter.tumblr.com
// @icon 	http://i.imgur.com/ejsZR8A.png
// @include     https://www.tumblr.com/dashboard
// @include     http://www.tumblr.com/dashboard
// @version     v1.0
// @grant       none
// ==/UserScript==
var minutesCountdown = 1; //Minutes in which notifications are checked, you can change it for values>1. Default value is set to 1
var tumblrNotifier = function(){
	console.log("Tumblr Notifier: started");
	function sendRequest(){
		var xmlReq = new XMLHttpRequest();
		xmlReq.open("GET", "https://www.tumblr.com/", true);
			xmlReq.onload=function(e){
			var httpText = xmlReq.responseText;
			var toSearch = "<div class=\"tab_notice inbox_notice_container\"><span class=\"tab_notice_value\">";//25
			var notifications = "";
				for(var i=0;i<httpText.length;i++){
					if(httpText.substring(i,i+toSearch.length)==toSearch){
					i=i+toSearch.length;
					while(httpText[i]!='<'){
						notifications+=httpText[i];
						i++;
					}
					if(notifications=="0")
						return;
					notifyMe(notifications);
					return;
				}
			}
		}
		xmlReq.send();
	}
		function notifyMe(notifications) {
		if (!("Notification" in window)) {
			alert("This browser does not support desktop notification");
		}

		else if (Notification.permission === "granted") {
			var img = "http://i.imgur.com/ejsZR8A.png";
			var text = "You have "+notifications+" messages!";
			var notification = new Notification('Tumblr Notifications',{ body: text, icon: img });
		}
		else if (Notification.permission !== 'denied') {
			Notification.requestPermission(function (permission) {

			if(!('permission' in Notification)) {
				Notification.permission = permission;
			}

			if (permission === "granted") {
				var img = "http://i.imgur.com/ejsZR8A.png";
				var text = "You have "+notifications+" messages!";
				var notification = new Notification('Tumblr Notifications',{ body: text, icon: img });
			}
			});
		}
	}
	setInterval(sendRequest,minutesCountdown*60000);
}();
